﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using ZBJF.Warranty.BLL.Cached;

namespace ZBJF.Warranty.BLL.SMS
{
    public class SMSHelper
    {
        static string SignName = "中保金服";//签名
        static string product = "Dysmsapi";//短信API产品名称
        static string domain = "dysmsapi.aliyuncs.com";//短信API产品域名
        static string accessId = "LTAI2DBlGYH0qtil";
        static string accessSecret = "1yrYf0V96U7fw72xKWZO8CLXZddOXw";
        static string regionIdForPop = "cn-hangzhou";
        /// <summary>
        /// App激活时验证码模版CODE
        /// </summary>
        public static string VerificationCodeTemp = "SMS_109355464";
        private  static bool SendSMS(string mobiles, string content,ref string resMsg)
        {
            var appConfig = AppConfigCached.GetAppConfig();
            string pwd = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(appConfig.SMSPassword));//密码要Base64编码
            string urltem = appConfig.SMSUrl;//"http://www.qz876.com/servlet/UserServiceAPI";
            string method = "sendSMS";
            //先GBK编码,然后UrlEncode编码
            string msg = HttpUtility.UrlEncode(Encoding.GetEncoding("GBK").GetBytes(content));

            string url = urltem + "?method=" + method + "&username=" + appConfig.SMSUserName + "&password=" + pwd +
                "&smstype=1&mobile=" + mobiles + "&content=" + msg;

            WebRequest myRequest = WebRequest.Create(url);
            WebResponse myResponse = myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream());
            var result = reader.ReadToEnd().ToLower();
            resMsg = result;
            return result.StartsWith("success");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mobiles">手机号，多个用逗号分隔</param>
        /// <param name="verificationCode">验证码Code，长度小于等于6</param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool SendVerificationCodeSMS(string mobiles, string verificationCode, ref string msg)
        {
            IClientProfile profile = DefaultProfile.GetProfile(regionIdForPop, accessId, accessSecret);
            DefaultProfile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            try
            {
                //request.SignName = "上云预发测试";//"管理控制台中配置的短信签名（状态必须是验证通过）"
                //request.TemplateCode = "SMS_71130001";//管理控制台中配置的审核通过的短信模板的模板CODE（状态必须是验证通过）"
                //request.RecNum = "13567939485";//"接收号码，多个号码可以逗号分隔"
                //request.ParamString = "{\"name\":\"123\"}";//短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                //SingleSendSmsResponse httpResponse = client.GetAcsResponse(request);
                request.PhoneNumbers = mobiles;
                request.SignName = SignName;
                request.TemplateCode = VerificationCodeTemp;
                request.TemplateParam = "{\"code\":\"" + verificationCode + "\"}";
                request.OutId = "xxxxxxxx";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                if (sendSmsResponse == null)
                {
                    msg = "请求发送短信失败.";
                    return false;
                }
                else
                {
                    msg = sendSmsResponse.Message;
                    return sendSmsResponse.Code == "OK";
                }
            }
            catch (ServerException e)
            {
                msg = "ServerException";
                return false;
                //System.Console.WriteLine("ServerException");
            }
            catch (ClientException e)
            {
                msg = "ClientException";
                return false;
                //System.Console.WriteLine("ClientException");
            }
        }
    }
}
